package com.kbbywyclient.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.util.FileUtils;
import com.kbbywyclient.util.ImageUtil;
import com.kbbywyclient.util.LogUtil;
import com.kbbywyclient.util.RsaJsonUtil;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.BottomPopupOptionWeb;
import com.kbbywyclient.widget.CustomToolBar;
import com.kbbywyclient.widget.ProgressWebView;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;

/**
 * Description:
 * Created by FHW
 * on 2017/5/11
 */

public class AddProductActivity extends BaseActivity {

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.wv_contact)
    ProgressWebView wv_contact;

    private RsaJsonUtil rsaJsonUtil;
    private String params = "";

    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    public static final int REQ_CHOOSE = 1;
    private static final int FILECHOOSER_RESULTCODE = 2;

    private String mCurrentPhotoPath = "";//保存当前图片路径

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_add_product;
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("添加产品");
    }

    @Override
    protected void initView() {
        v_toolbar.setLeftViewOnClickLinster(v -> finish());

        rsaJsonUtil = new RsaJsonUtil();

        //设置webview
        wv_contact.getSettings().setDefaultTextEncodingName("UTF-8");
        //webview自适应屏幕
        WebSettings settings = wv_contact.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //                    settings.setBuiltInZoomControls(true); //显示放大缩小
        //                    settings.setSupportZoom(true); //可以缩放
        // webview自适应第二种
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        wv_contact.setSaveEnabled(true);
        settings.setJavaScriptEnabled(true); // 设置支持javascript脚本

        // 添加js交互接口类，并起别名 jsInterface
//        wv_contact.addJavascriptInterface(new JSInterface(this), "jsInterface");

        wv_contact.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;

            }
        });

        wv_contact.setWebChromeClient(new WebChromeClient() {
            //3.0++
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                openFileChooserImpl(uploadMsg);
            }

            //3.0--
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooserImpl(uploadMsg);
            }

            //4.1++
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooserImpl(uploadMsg);
            }

            //5.0 +
            @Override
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                openFileChooserImplForAndroid5(filePathCallback);
                return true;
            }
        });

        rsaJsonUtil.put("SalesID", PreUtils.getUser(this).getSalesID() + "");
        params = rsaJsonUtil.getRsaParams();
        String url = API.ADD_PRODUCT + "?params=" + params;
        LogUtil.d(url);
        wv_contact.loadUrl(url);

    }

    @Override
    public void initData() {

    }

    @Override
    public void initAppComponent(AppComponent appComponent) {

    }

    //5.0以上
    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadCallbackAboveL = uploadMsg;
        selectImgDialog();
    }

    //5.0以下的掉用
    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        selectImgDialog();
    }

    private void selectImgDialog() {
        BottomPopupOptionWeb bottomPopupOption = new BottomPopupOptionWeb(this);
        bottomPopupOption.setItemText("拍 照", "手机相册");
        bottomPopupOption.setItemClickListener(position -> {
            switch (position) {
                case 0://拍 照
                    takePhoto();
                    break;
                case 1://手机相册
                    chosePic();
                    break;
            }
            bottomPopupOption.dismiss();
        });
        bottomPopupOption.setOnClickAllListener(() -> {
            cleanCallback();
            bottomPopupOption.dismiss();
        });
        bottomPopupOption.showPopupWindow();
    }

    private void cleanCallback() {
        if (mUploadCallbackAboveL != null) {
            mUploadCallbackAboveL.onReceiveValue(null);
            mUploadCallbackAboveL = null;
        } else if (mUploadMessage != null) {
            mUploadMessage.onReceiveValue(null);
            mUploadMessage = null;
        }
    }

    private void takePhoto() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            Uri imageUri = null;
            try {
                imageUri = Uri.fromFile(createImageFile());
            } catch (IOException e) {
                e.printStackTrace();
            }
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(takePictureIntent, FILECHOOSER_RESULTCODE);
        }
    }

    private void chosePic() {
        Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        String IMAGE_UNSPECIFIED = "image/*";
        innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
        Intent wrapperIntent = Intent.createChooser(innerIntent, null);
        startActivityForResult(wrapperIntent, REQ_CHOOSE);
    }

    //创建文件夹包装图片
    private File createImageFile() throws IOException {
        File storageDir = new File(FileUtils.getStorageDirectory());
        if (!storageDir.exists()) {
            storageDir.mkdirs();
        }
        storageDir = new File(FileUtils.getStorageDirectory() + "/", System.currentTimeMillis() + ".jpg");
        //保存当前图片路径
        mCurrentPhotoPath = storageDir.getAbsolutePath();
        return storageDir;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
        Uri result = null;
        if (data != null) {
            switch (requestCode) {
                case FILECHOOSER_RESULTCODE://相机
                    File file = new File(mCurrentPhotoPath);
                    result = Uri.fromFile(file);
                    break;
                case REQ_CHOOSE://相册
                    if (Build.VERSION.SDK_INT == 19) {//解决4.4.x本地图片 上传不了问题
                        File file1 = new File(ImageUtil.getImageAbsolutePath(this, data.getData()));
                        result = Uri.fromFile(file1);
                    } else {
                        result = data.getData();
                    }
                    break;
            }
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
                LogUtil.d(result.toString());
            }
        } else {
            cleanCallback();
        }

    }

    //5.0以上版本，由于api不一样，要单独处理
//    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, Intent data) {
        if (mUploadCallbackAboveL == null) {
            return;
        }
        Uri result = null;
        if (requestCode == FILECHOOSER_RESULTCODE) {
            File file = new File(mCurrentPhotoPath);
            Uri localUri = Uri.fromFile(file);
            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
            sendBroadcast(localIntent);
            result = Uri.fromFile(file);

        } else if (requestCode == REQ_CHOOSE) {
            result = data.getData();
        }
        mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
        mUploadCallbackAboveL = null;
        LogUtil.d(result.toString());
        return;
    }


}
